package com.rwy.web.controller;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.web.ErrorAttributes;
import org.springframework.boot.autoconfigure.web.ErrorController;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.ModelAndView;

import com.rwy.web.filter.authorize.AuthorizeStatus;

import lombok.extern.log4j.Log4j;

@Controller 
@Log4j
public class RWYErrorController implements ErrorController {  
  
 private static final String ERROR_PATH = "/error";  
 @Autowired
 private ErrorAttributes errorAttributes;


 public ModelAndView errorHtml(HttpServletRequest request) {
     return new ModelAndView("greeting", getErrorAttributes(request, false));
 }

 /**
  * Supports other formats like JSON, XML
  * @param request
  * @return
  */
 @RequestMapping(value = ERROR_PATH)
 @ResponseBody
 public AuthorizeStatus error(HttpServletRequest request) {
     Map<String, Object> body = getErrorAttributes(request, getTraceParameter(request));
     log.error(body);
     return new AuthorizeStatus("400", "bad request", body.get("path") == null? body.get("URL").toString(): body.get("path").toString());
 }
 
 private boolean getTraceParameter(HttpServletRequest request) {
     String parameter = request.getParameter("trace");
     if (parameter == null) {
         return false;
     }
     return !"false".equals(parameter.toLowerCase());
 }

 private Map<String, Object> getErrorAttributes(HttpServletRequest request,
                                                boolean includeStackTrace) {     
     RequestAttributes requestAttributes = new ServletRequestAttributes(request);       
     Map<String, Object> map = this.errorAttributes.getErrorAttributes(requestAttributes,includeStackTrace);  
     String URL = request.getRequestURL().toString();
     map.put("URL", URL);        
     return map;
 }
 
 @Override  
 public String getErrorPath() {  
  return ERROR_PATH;  
 }  
  
}  